import UIKit

open class YAppDelegate: UIResponder, UIApplicationDelegate {

    public var window: UIWindow?

    final public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        onYConfig()
        if YConfig.yCrashHandlerAble {
            NSSetUncaughtExceptionHandler { exception in
                let timeFormatter = DateFormatter()
                timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                let time = "异常时间：\(timeFormatter.string(from: Date()))"
                let device = "设备：\(YDeviceUtils.getDeviceName())_\(YDeviceUtils.getDeviceVersion())"
                let deviceID = "设备识别码：\(YDeviceUtils.getDeviceID())"
                let ipaVersion = "ipa版本号：\(YAppUtils.getAppVersionCode())_\(YAppUtils.getAppVersionName())"
                let exceptionMsg = "异常类型：\(exception.name)\n异常原因：\(exception.reason!)\n异常详情：\(exception.callStackSymbols.joined(separator: "\n\t\t\t"))"
                let message = "\(time)\n\(device)\n\(deviceID)\n\(ipaVersion)\n\(exceptionMsg)"
                print(message)
                if YConfig.commitErrorLog != nil {
                    let semaphore = DispatchSemaphore(value: 0)
                    URLSession.shared.dataTask(with: YAppDelegate.getRequestByRequest(viewController: nil,ip:YConfig.IP, jkid: YConfig.commitErrorLog!, inputJsonKV:YJsonKV().put("msg", message), httpMethod: "POST") , completionHandler: { (_, _ , _) -> Void in
                        semaphore.signal()
                    }).resume()
                    _ = semaphore.wait(timeout: DispatchTime.distantFuture)
                }
            }
        }
        initIQKeyBoard()
        onYCreated()
        //去掉navbar下划线
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
        UINavigationBar.appearance().shadowImage = UIImage()
        return true
    }

    open func onYConfig(){}
    
    open func onYCreated(){}
    
    func initIQKeyBoard(){
        let manager = IQKeyboardManager.shared
        manager.enable = true
        manager.shouldResignOnTouchOutside = true
        manager.shouldPlayInputClicks = true
        manager.shouldShowToolbarPlaceholder = true
        // manager.shouldFixInteractivePopGestureRecognizer = true
        // manager.shouldGroupAccessibilityChildren = true
        manager.shouldToolbarUsesTextFieldTintColor = true
        manager.enableAutoToolbar = true
        manager.toolbarDoneBarButtonItemText = "收起"
    }
    
    public static func getRequestByRequest(viewController:YUIViewController?,ip:String,jkid:String,inputJsonKV:YJsonKV?,httpMethod:String)->URLRequest{
        var request = URLRequest(url:URL(string:"\(ip)")!)
        var params = "jkid=\(jkid)&jkparam=".replacingOccurrences(of: "+", with: "%2b")
        let httpBodyData:Data?
        request.httpMethod = httpMethod
        request.timeoutInterval = TimeInterval(YConfig.timeOut)
        if let jsonDic = inputJsonKV?.jsonKVDic,jsonDic.count > 0,JSONSerialization.isValidJSONObject(jsonDic) {
            let jsonStr = (NSString(data:try! JSONSerialization.data(withJSONObject: jsonDic, options: []) ,encoding: String.Encoding.utf8.rawValue)! as String).replacingOccurrences(of: "+", with: "%2b")
            viewController?.yPrint("\(jkid):request:\(jsonStr)")
            params += YConfig.encryptParamsAble ? YAESCrypt.encrypt(jsonStr, password: YConfig.encryptParamsKey) : jsonStr
        }else{
            viewController?.yPrint("\(jkid):request:无入参")
            params += YConfig.encryptParamsAble ? YAESCrypt.encrypt("", password: YConfig.encryptParamsKey) : ""
        }
        httpBodyData = params.data(using: .utf8)!
        if YConfig.compressParamsAble {
            request.httpBody = try! httpBodyData?.gzipped().base64EncodedString().addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!.data(using: .utf8)
            request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")
        }else{
            request.httpBody = httpBodyData
        }
        if let onHTTPHeader = YConfig.onHTTPHeader{
            onHTTPHeader(&request)
        }
        return request
    }

//    public func applicationWillResignActive(_ application: UIApplication) {
//    }
//
//    public func applicationDidEnterBackground(_ application: UIApplication) {
//    }
//
//    public func applicationWillEnterForeground(_ application: UIApplication) {
//    }
//
//    public func applicationDidBecomeActive(_ application: UIApplication) {
//    }
//
//    public func applicationWillTerminate(_ application: UIApplication) {
//    }
}
